from typing import List

import cv2
import numpy as np
from captcha_recognizer.slider import Slider
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

app = FastAPI()

# 允许跨域
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
def hello_captcha():
    return {"Hello": "Captcha"}


class DetectionResult(BaseModel):
    box: List[int]  # [x1, y1, x2, y2]
    confidence: float
    message: str = None


@app.post("/captcha", response_model=DetectionResult)
async def captcha(
        file: UploadFile = File(...)):

    contents = await file.read()

    # 将字节流转换为numpy数组
    nparr = np.frombuffer(contents, np.uint8)
    image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

    if image is None:
        return DetectionResult(box=[], confidence=0, message="不支持的图片")

    box, confidence = Slider().identify(source=image)
    # box元素 float转为int
    box = [int(x) for x in box]
    return DetectionResult(box=box, confidence=confidence)
